package com.traffic.between.service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.traffic.between.config.BetweenProperties;



public class WeiLiuServiceImpl {
	private static Logger logger = Logger.getLogger(WeiLiuServiceImpl.class);
	public static WeiLiuServiceImpl service = new WeiLiuServiceImpl();
	
	private static String HOST_ORDER_PATH =BetweenProperties.WEILIU_ORDER_URL;
	private static String HOST_ORDERSTATUS_PATH =BetweenProperties.WEILIU_ORDERSTATUS_URL;
	private static String WEILIU_ACCOUNT = BetweenProperties.WEILIU_ACCOUNT;
	private static String WEILIU_KEY = BetweenProperties.WEILIU_KEY;
	
	
	
	public String order(String pkgNo, String phoneNo, String tradeNo,String region) {
	
        String result = "";

		try {
			String waitSign = "account="+WEILIU_ACCOUNT+"&mobile="+phoneNo+"&package="+pkgNo+"&key="+WEILIU_KEY;
			String sign = getMD5(waitSign);
	        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
	        pairList.add(new BasicNameValuePair("Action","charge"));
	        pairList.add(new BasicNameValuePair("V","1.1"));
	        pairList.add(new BasicNameValuePair("Range","0"));
	        pairList.add(new BasicNameValuePair("OutTradeNo",tradeNo));
	        pairList.add(new BasicNameValuePair("Account",WEILIU_ACCOUNT));
	        pairList.add(new BasicNameValuePair("Mobile",phoneNo));
	        pairList.add(new BasicNameValuePair("Package",pkgNo));
	        pairList.add(new BasicNameValuePair("Sign",sign));
	        logger.info("微流在线订购请求参数："+pairList);
			HttpPost httpPost = new HttpPost(HOST_ORDER_PATH);
			CloseableHttpClient client = HttpClients.createDefault();
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
	
			
			if (200 == statusCode) {
				result = EntityUtils.toString(response.getEntity(), "utf-8");
			
			}
			 logger.info("微流在线訂購返回参数："+result);
		} catch (Exception e) {
			 logger.info("微流在线訂購請求異常："+e.getMessage());
		}

	
		return result;
	}

	
	
	
	public String orderStatus(String cstmOrderNo) {
		
	
	    List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        pairList.add(new BasicNameValuePair("Action",""));
        pairList.add(new BasicNameValuePair("V","1.1"));
        pairList.add(new BasicNameValuePair("Account",""));
        pairList.add(new BasicNameValuePair("Count",""));
        pairList.add(new BasicNameValuePair("Sign", ""));
       
      
        String result = "";  
		
		try {
			
			HttpPost httpPost = new HttpPost(HOST_ORDERSTATUS_PATH);
			CloseableHttpClient client = HttpClients.createDefault();
		
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			
		
			
			
		
			
			if (200 == statusCode) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, "utf-8");
			
			}
		} catch (Exception e) {
			
			Map<String,Object> map = new HashMap<String, Object>();
			map.put("err","-1");
			map.put("msg",e.getMessage());
			result =  new Gson().toJson(map);
		}
		return result;
	}

	
	
	

	/**
	 * md5加密 ，用于生成sign
	 * 
	 * @param message
	 * @return
	 */
	public static String getMD5(String message) {
		System.out.println("getMD5STR " + message);
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		System.out.println("getMD5====>" + md5StrBuff.toString().toLowerCase());
		return md5StrBuff.toString().toLowerCase();// 字母小写
	}


	public static void main(String[] args) throws UnsupportedEncodingException {
//		Map<String, Object> params = new HashMap<String, Object>();
//		params.put("chOrderId", "");//seqId, productCode, pkey, phoneNo , loginName
//		params.put("chId", "");//seqId, productCode, pkey, phoneNo , loginName
//		//params.put("agCodeProId", "");//seqId, productCode, pkey, phoneNo , loginName
//		//params.put("type", "");//seqId, productCode, pkey, phoneNo , phoneNo
//		//params.put("mobiles", "");//seqId, productCode, pkey, phoneNo , loginName
//		params.put("timestamp", "");//seqId, productCode, pkey, phoneNo , loginName
//		//params.put("loginName", "");//seqId, productCode, pkey, phoneNo , loginName
//		Object[] keys = params.keySet().toArray();
//		Arrays.sort(keys);//升序
//		for (Object key : keys) {
//			System.out.println(key);
//		}
       //String result =  new WeiLiuServiceImpl().order(pkgNo, phoneNo, tradeNo);
       //System.out.println(result);
		System.out.println(URLEncoder.encode("123","utf-8"));
		System.out.println(URLDecoder.decode("123","utf-8"));
	}


	
}
